package com.kk.score.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kk.score.entity.UserEntity;
import com.kk.score.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.Set;

@Service  //将类加入到spring容器中
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;  //调用业务层

    /**
     * 重新父类方法
     *
     * @param username 用户账号
     * @return spring security自动封装之后的用户
     * @throws UsernameNotFoundException 抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户账号信息
        UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUsername, username));
        //存储角色集合
        Set<GrantedAuthority> authorities = new LinkedHashSet<>();
        if (user == null) {
            throw new UsernameNotFoundException("当前用户名不存在！");
        }
        //添加角色，角色必须以`ROLE_`开头。
        if (user.getStatus() == 0) {
            throw new LockedException("账号不可用");
        } else if (user.getStatus() == 1) {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        } else if(user.getStatus() == 2){
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        user.setAuthorities(authorities);
        return user;
    }
}